package com.bdqn.design.proxy.jdk;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * transactionInvocationHandler
 *
 * @author LILIBO
 * @since 2025/1/8
 */
public class TransactionInvocationHandler implements InvocationHandler {

    /**
     * 日志
     */
    private final Logger log = LogManager.getLogger(TransactionInvocationHandler.class);

    /**
     * 被代理的目标对象
     */
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }

    /**
     * 为被代理的接口方法定义的代理业务规则
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 执行真实方法之前
        start(proxy, method, args);
        Object feedback = null;
        // 通过反射执行目标对象的实际业务
        try {
            feedback = method.invoke(target, args);
            commit(feedback);
        } catch (Exception e) {
            rollBack(e);
        }
        return feedback;
    }

    /**
     * 事务开始
     */
    private void start(Object proxy, Method method, Object[] args) {
        log.info("事务开始\t[set autoCommit=0; start;]");
    }

    /**
     * 事务回滚
     *
     * @param e
     */
    private void rollBack(Exception e) {
        log.error("发生了异常：" + e.getMessage());
        log.info("事务回滚\t[rollback;]");
    }

    /**
     * 事务提交
     */
    private void commit(Object feedback) {
        log.info("事务提交\t[commit;]");
    }

}
